import { useState } from "react";
import { PlusCircle } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Toaster } from "@/components/ui/sonner";
import { toast } from "sonner";
import { CreateRoleDialog } from "./CreateRoleDialog";
import { EditRoleDialog } from "./EditRoleDialog";

export function RoleTab({ roles, users, onEditRole, onDeleteRole }) {
  const [showCreateRoleDialog, setShowCreateRoleDialog] = useState(false);
  const [editingRole, setEditingRole] = useState(null);
  const [showEditRoleDialog, setShowEditRoleDialog] = useState(false);
  const [roleToDelete, setRoleToDelete] = useState(null);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);

  const handleEditClick = (role) => {
    setEditingRole(role);
    setShowEditRoleDialog(true);
  };

  const handleDeleteClick = (role) => {
    setRoleToDelete(role);
    setShowDeleteDialog(true);
  };

  const confirmDelete = () => {
    if (roleToDelete) {
      onDeleteRole(roleToDelete.id);
      toast("角色已删除");
      setShowDeleteDialog(false);
      setRoleToDelete(null);
    }
  };

  return (
    <>
      <Toaster />
      <Card>
        <CardHeader>
          <div className='flex justify-between items-center'>
            <CardTitle>角色管理</CardTitle>
            <Button onClick={() => setShowCreateRoleDialog(true)}>
              <PlusCircle className='mr-2 h-4 w-4' />
              创建角色
            </Button>
          </div>
          <CardDescription>
            创建和管理系统角色，分配给用户相应的权限
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>角色名称</TableHead>
                <TableHead>描述</TableHead>
                <TableHead>用户数量</TableHead>
                <TableHead>操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {roles.map((role) => (
                <TableRow key={role.id}>
                  <TableCell className='font-medium'>{role.name}</TableCell>
                  <TableCell>{role.description}</TableCell>
                  <TableCell>
                    {users.filter((user) => user.role === role.name).length}
                  </TableCell>
                  <TableCell>
                    <div className='flex gap-2'>
                      <Button
                        variant='outline'
                        size='sm'
                        onClick={() => handleEditClick(role)}
                      >
                        编辑
                      </Button>
                      {role.name !== "管理员" && (
                        <Button
                          variant='outline'
                          size='sm'
                          className='text-red-600'
                          onClick={() => handleDeleteClick(role)}
                        >
                          删除
                        </Button>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      <CreateRoleDialog
        open={showCreateRoleDialog}
        onOpenChange={setShowCreateRoleDialog}
      />

      {editingRole && (
        <EditRoleDialog
          role={editingRole}
          open={showEditRoleDialog}
          onOpenChange={setShowEditRoleDialog}
          onSave={(updatedRole) => {
            onEditRole(updatedRole);
            toast.success("角色已更新", {
              description: `角色 "${updatedRole.name}" 已成功更新。`,
            });
            setShowEditRoleDialog(false);
            setEditingRole(null);
          }}
        />
      )}

      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确定要删除这个角色吗？</AlertDialogTitle>
            <AlertDialogDescription>
              {roleToDelete &&
                `删除角色 "${roleToDelete.name}" 后将无法恢复。此操作可能会影响已分配此角色的用户权限。`}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmDelete}
              className='bg-red-600 hover:bg-red-700'
            >
              删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}
